#!/bin/bash

#set -o nounset
#set -o errexit
#set -o xtrace

RED='\033[0;31m'
GREEN='\033[32;1m'
YELLOW='\033[33;1m'
NC='\033[0m' # No Color

# default version, can be overridden by cmd line options
export CONSOLE=${CONSOLE:-false}
os_type=$(cat /etc/os-release | grep "^ID=" | awk -F= '{print $2}' | tr -d [:punct:])
os_version_id=$(cat /etc/os-release | grep "VERSION_ID=" | awk -F= '{print $2}' | tr -d [:punct:])

# Check whether the current system user is root
if [ "$EUID" -ne 0 ]; then
    if [ "$LANG" == "zh_CN.UTF-8" ]; then
        echo -e "${RED}[ERROR] 当前用户不是 root 用户，请切换到 root 用户执行该脚本.${NC}"
        exit 1
    else
        echo -e "${RED}[ERROR] Current user is not root user, please switch to root user to execute the script.${NC}"
        exit 1
    fi
fi

if [ -z "$SSH_RSA" ]; then
    if [ "$LANG" == "zh_CN.UTF-8" ]; then
        echo -e "${RED}[ERROR] 请设置环境变量 SSH_RSA, 该变量为 SSH 公钥.${NC}"
        exit 1
    else
        echo -e "${RED}[ERROR] Please set the environment variable SSH_RSA, the variable is SSH public key.${NC}"
        exit 1
    fi
fi

function check_docker() {
    if systemctl status docker | grep Active | grep -q running; then
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${GREEN}[INFO] Docker 服务已经安装在主机上.${NC}"
        else
            echo -e "${GREEN}[INFO] The docker service has been installed on the host.${NC}"
        fi
    else
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${RED}[INFO] 未检测到 Docker 服务, 请执行该脚本安装 Docker 服务, 'curl -sfL https://get.rainbond.com/install_docker | bash'.${NC}"
            exit 1
        else
            echo -e "${RED}[INFO] No Docker service is detected. Run this script to install the Docker service, 'curl -sfL https://get.rainbond.com/install_docker | bash'.${NC}"
            exit 1
        fi
    fi
}

function add_user_in_ubuntu() {
    useradd --create-home -s /bin/bash -g root "$1"
    echo "$1":"$2" | chpasswd
    if [ "$LANG" == "zh_CN.UTF-8" ]; then
        echo -e "${GREEN}[INFO] 用户 $1 已经创建.${NC}"
    else
        echo -e "${GREEN}[INFO] User $1 has been created.${NC}"
    fi
}

function add_user_in_redhat() {
    adduser -g root "$1"
    echo "$1":"$2" | chpasswd
    if [ "$LANG" == "zh_CN.UTF-8" ]; then
        echo -e "${GREEN}[INFO] 用户 $1 已经创建.${NC}"
    else
        echo -e "${GREEN}[INFO] User $1 has been created.${NC}"
    fi
}

function add_user() {
    user=${DOCKER_USER:-"docker"}
    pass=${DOCKER_PASS:-'rbd-123465!'}
    
    if ! grep -q docker /etc/group; then
        groupadd --force docker
    fi

    if id -u "$user" >/dev/null 2>&1; then
        if ! id -nG "$user" | grep -qw "docker"; then
            gpasswd -a "$user" docker
        fi
        
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${GREEN}[INFO] 用户 $user 已经存在.${NC}"
        else
            echo -e "${GREEN}[INFO] User $user already exists.${NC}"
        fi
    else
        case $os_type in
        centos|redhat|euleros|fusionos|anolis|kylin|rhel|rocky|fedora|openEuler)
            add_user_in_redhat "$user" "$pass"
        ;;
        ubuntu|debian)
            add_user_in_ubuntu "$user" "$pass"
        ;;
        *)
            if [ "$LANG" == "zh_CN.UTF-8" ]; then
                echo -e "${RED}[ERROR] 暂不支持 $os_type 操作系统.${NC}"
                exit 1
            else
                echo -e "${RED}[ERROR] The $os_type operating system is temporarily not supported.${NC}"
                exit 1
            fi
        ;;
        esac
    fi

    $CONSOLE || add_ssh_rsa "$user"
}

function add_ssh_rsa() {
    
    if id -u "$user" >/dev/null 2>&1; then
        if [ ! -d "/home/$1/.ssh" ]; then
            if [ "$LANG" == "zh_CN.UTF-8" ]; then
                echo -e "${GREEN}[INFO] 创建 /home/$1/.ssh 目录.${NC}"
            else
                echo -e "${GREEN}[INFO] Create /home/$1/.ssh directory.${NC}"
            fi
            mkdir -p /home/"$1"/.ssh
        fi
        if [ -f "/home/$1/.ssh/authorized_keys" ]; then
            if [ "$LANG" == "zh_CN.UTF-8" ]; then
                echo -e "${GREEN}[INFO] /home/$1/.ssh/authorized_keys 已经存在.${NC}"
            else
                echo -e "${GREEN}[INFO] /home/$1/.ssh/authorized_keys already exists.${NC}"
            fi
            chmod 777 /home/"$1"/.ssh/authorized_keys
            if ! < /home/"$1"/.ssh/authorized_keys grep -q "$SSH_RSA"; then
                echo "$SSH_RSA" >> /home/"$1"/.ssh/authorized_keys
            fi
        else
            if [ "$LANG" == "zh_CN.UTF-8" ]; then
                echo -e "${GREEN}[INFO] 创建 /home/$1/.ssh/authorized_keys.${NC}"
            else
                echo -e "${GREEN}[INFO] Create /home/$1/.ssh/authorized_keys.${NC}"
            fi
            touch /home/"$1"/.ssh/authorized_keys
            chmod 777 /home/"$1"/.ssh/authorized_keys
            echo "$SSH_RSA" > /home/"$1"/.ssh/authorized_keys
        fi

        if < /home/"$1"/.ssh/authorized_keys grep -q "$SSH_RSA"; then
            if [ "$LANG" == "zh_CN.UTF-8" ]; then
                echo -e "${GREEN}[INFO] 成功将 SSH 公钥添加到 /home/$1/.ssh/authorized_keys.${NC}"
            else
                echo -e "${GREEN}[INFO] Successfully added ssh public key to /home/$1/.ssh/authorized_keys.${NC}"
            fi
        else
            if [ "$LANG" == "zh_CN.UTF-8" ]; then
                echo -e "${RED}[ERROR] 将 SSH 公钥添加到 /home/$1/.ssh/authorized_keys 失败.${NC}"
                exit 1
            else
                echo -e "${RED}[ERROR] Add ssh public key to /home/$1/.ssh/authorized_keys failed.${NC}"
                exit 1
            fi
        fi
        chmod 600 /home/"$1"/.ssh/authorized_keys
        chown -R "$1":"$1"  /home/"$1"/.ssh
    fi
}

function check_user_permission(){
    if su "docker" -c "docker ps" >/dev/null 2>&1; then
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${GREEN}[INFO] Docker 用户有权限执行 docker 命令.${NC}"
        else
            echo -e "${GREEN}[INFO] Docker users have the permission to execute docker commands.${NC}"
        fi
    else
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${RED}[ERROR] Docker 用户无权限执行 docker 命令, 请尝试重启docker 'systemctl restart docker'. 重启 docker 后, 再次执行该脚本.${NC}"
            exit 1
        else
            echo -e "${RED}[ERROR] Docker users have no permission to execute docker commands, Please try to restart docker 'systemctl restart docker'. After restarting docker, execute the script again.${NC}"
            exit 1
        fi
    fi
}

function disable_firewalld() {
    if systemctl status firewalld | grep Active | grep -q running >/dev/null 2>&1; then
        systemctl stop firewalld >/dev/null 2>&1
        systemctl disable firewalld >/dev/null 2>&1
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${GREEN}[INFO] 检测到 Firewalld 服务已启动，正在将 Firewalld 服务关闭并禁用.${NC}"
        else
            echo -e "${GREEN}[INFO] The Firewalld service has been started, Firewalld service is being turned off and disabled.${NC}"
        fi
    else
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${GREEN}[INFO] Firewalld 服务未安装.${NC}"
        else
            echo -e "${GREEN}[INFO] Firewalld service is not installed.${NC}"
        fi
    fi
}

function disable_swap() {
    if swapoff -a; then
        sed -i '/swap/s/^/#/' /etc/fstab
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${GREEN}[INFO] swap 已经禁用.${NC}"
        else
            echo -e "${GREEN}[INFO] swap has been disabled.${NC}"
        fi
    fi    
}

function check_time_sync() {

    if timedatectl status | grep "NTP synchronized" | grep -q "yes" >/dev/null 2>&1 || timedatectl show | grep "NTPSynchronized=yes" >/dev/null 2>&1; then
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${GREEN}[INFO] NTP 时间同步已经启用.${NC}"
        else
            echo -e "${GREEN}[INFO] NTP time synchronization has been enabled.${NC}"
        fi
    else
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${YELLOW}[WARN] NTP 时间同步未启用.${NC}"
        else
            echo -e "${YELLOW}[WARN] NTP time synchronization is not enabled.${NC}"
        fi
    fi
}

function check_resource(){
    cpu=$(grep -c 'processor' /proc/cpuinfo)
    mem=$(free -g | awk '/^Mem/{print $2}')
    DISK_SPACE=$(df /|sed -n '2p'|awk '{print $2}')

    # check cpu
    if [ "${cpu}" -lt 2 ]; then
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${YELLOW}[WARN] CPU核数建议至少为2核.${NC}"
        else
            echo -e "${YELLOW}[WARN] The cpu is recommended to be at least 2C.${NC}"
        fi
    fi

    # check memory
    if [ "${mem}" -lt 3 ]; then
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${YELLOW}[WARN] 内存建议至少为8G.${NC}"
        else
            echo -e "${YELLOW}[WARN] The Memory is recommended to be at least 8G.${NC}"
        fi
    fi

    # check disk space
    if [ "${DISK_SPACE}" -lt 47185920 ];then
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${YELLOW}[WARN] 根分区空间需大于 50G.${NC}"
        else
            echo -e "${YELLOW}[WARN] The root partition space must be greater than 50G.${NC}"
        fi
    fi
}

function check_kernel() {
    kernel_version=$(uname -r | awk -F. '{print $1}')
    if [ "$kernel_version" -lt "4" ]; then 
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${YELLOW}[WARN] 内核版本必须高于4.0, 请尽快升级内核到4.0+.${NC}"
        else
            echo -e "${YELLOW}[WARN] Kernel version must be higher than 4.0, Please upgrade the kernel to 4.0+ as soon as possible.${NC}"
        fi
    fi
}

function check_nfscli(){
    case $os_type in
        ubuntu|debian)
            if dpkg -l | grep -q nfs-common >/dev/null 2>&1; then
                if [ "$LANG" == "zh_CN.UTF-8" ]; then
                    echo -e "${GREEN}[INFO] nfs-common 已经安装在主机上.${NC}"
                else
                    echo -e "${GREEN}[INFO] nfs-common has been installed on the host.${NC}"
                fi
            else
                if [ "$LANG" == "zh_CN.UTF-8" ]; then
                    echo -e "${YELLOW}[WARN] nfs-common 未安装在主机上, 请执行命令安装 'apt -y install nfs-common'.${NC}"
                else
                    echo -e "${YELLOW}[WARN] nfs-common is not installed on the host, please execute the command install 'apt-get update && apt -y install nfs-common'.${NC}"
                fi
            fi
        ;;
        *)
            if rpm -qa | grep -q nfs-utils >/dev/null 2>&1; then
                if [ "$LANG" == "zh_CN.UTF-8" ]; then
                    echo -e "${GREEN}[INFO] nfs-utils 已经安装在主机上.${NC}"
                else
                    echo -e "${GREEN}[INFO] nfs-utils has been installed on the host.${NC}"
                fi
            else
                if [ "$LANG" == "zh_CN.UTF-8" ]; then
                    echo -e "${YELLOW}[WARN] nfs-utils 未安装在主机上, 请执行命令安装 'yum -y install nfs-utils'.${NC}"
                else
                    echo -e "${YELLOW}[WARN] nfs-utils is not installed on the host, please execute the command install 'yum -y install nfs-utils'.${NC}"
                fi
            fi
        ;;
        esac
}


function check_openssh(){

    if ssh -V >/dev/null 2>&1; then
      OPENSSH_VERSION=$(ssh -V |& awk -F[_.] '{print $2}')
      if [ "${OPENSSH_VERSION}" -lt "7" ];then
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${RED}[ERROR] Openssh 版本必须高于 7.0.${NC}"
            exit 1
        else
            echo -e "${RED}[ERROR] Openssh version must be higher than 7.0 ${NC}"
            exit 1
        fi
      fi
    else
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${RED}[ERROR] 需要安装 7.0+ 版本的openssh.${NC}"
            exit 1
        else
            echo -e "${RED}[ERROR] Need to install 7.0+ version of openssh.${NC}"
            exit 1
        fi
    fi

    if grep -v "^\s*#" /etc/ssh/sshd_config | grep "AllowTcpForwarding yes" >/dev/null 2>&1; then
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${GREEN}[INFO] /etc/ssh/sshd_config 已经配置 AllowTcpForwarding yes.${NC}"
        else
            echo -e "${GREEN}[INFO] /etc/ssh/sshd_config has been configured AllowTcpForwarding yes.${NC}"
        fi
    else
        if grep "AllowTcpForwarding no" /etc/ssh/sshd_config >/dev/null 2>&1; then
            sed -i '/AllowTcpForwarding/s/^/#/' /etc/ssh/sshd_config
            sed -i '$a\AllowTcpForwarding yes' /etc/ssh/sshd_config
        else
            sed -i '$a\AllowTcpForwarding yes' /etc/ssh/sshd_config
        fi
        if [ "$LANG" == "zh_CN.UTF-8" ]; then
            echo -e "${YELLOW}[WARN] /etc/ssh/sshd_config 配置 AllowTcpForwarding yes 成功, 请执行命令重启 sshd 服务生效, 'systemctl restart sshd'.${NC}"
        else
            echo -e "${YELLOW}[WARN] /etc/ssh/sshd_config AllowTcpForwarding yes is successfully configured, Run the following command to restart the sshd service to take effect, 'systemctl restart sshd'.${NC}"
        fi
    fi
}

function init_syscfg(){
    curl -sfL https://get.rainbond.com/linux-optimize.sh | bash
}

function os_environment_configuration {
    # stop and disbale friewalld
    disable_firewalld

    # Close the swap partition permanently
    disable_swap

    # check time sync
    check_time_sync

    # check nfs-utils
    check_nfscli

    # check kernel version
    check_kernel

    # check os resource
    check_resource

    # check openssh version
    check_openssh

    # init system config
    init_syscfg
}

function docker_environment_configuration {
    # add docker user
    add_user

    # Check that docker is installed
    check_docker

    # check docker user permission
    check_user_permission
}

os_environment_configuration

docker_environment_configuration